package com.csdj.server.config;

import com.csdj.server.pojo.Admin;
import com.csdj.server.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Author zyq
 * @Date 2022/12/13 19:40
 * @ClassName: SecurityConfig
 * @Description: TODO
 * @Version 1.0
 * WebSecurityConfigurerAdapter  security的适配器
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private IAdminService adminService;

    @Autowired
    private ResultAuthenticationEntryPoint resultAuthenticationEntryPoint;

    @Autowired
    private ResultAccessDeniedHandler resultAccessDeniedHandler;

    @Autowired
    private CustomUrlDecisionManager customUrlDecisionManager;

    @Autowired
    private CustomFilter customFilter;

    /**
     * 自定义 登录逻辑 加入到security框架中的授权管理器中
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService())
                .passwordEncoder(passwordEncoder());
    }

    /**
     * 配置 security 地址放行 授权地址
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
       //csrf 防护
        http.csrf()
                .disable()
                //session 管理进行关闭
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //设置 放行的地址
                .authorizeRequests()
                .antMatchers("/login","/logout")
                .permitAll()
                //所有的请求 必须通过认证
                .anyRequest()
                .authenticated()
                //配置动态权限 配置url菜单哪些角色能访问
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {

                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setAccessDecisionManager(customUrlDecisionManager);
                        object.setSecurityMetadataSource(customFilter);
                        return object;
                    }
                })
                .and()
                //关闭 缓存
                .headers()
                .cacheControl();
        //添加 过滤器
       http.addFilterBefore(jwtAuthenticationTokenFilter(),
               UsernamePasswordAuthenticationFilter.class);

       //消息通知器
        http.exceptionHandling()
                .accessDeniedHandler(resultAccessDeniedHandler)
                .authenticationEntryPoint(resultAuthenticationEntryPoint);
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        //统一配置 静态资源目录的放行
        web.ignoring()
                .antMatchers(
                        "/login",
                        "/logout",
                        "/css/**",
                        "/js/**",
                        "/index.html",
                        "/favicon.ico",
                        "/doc.html",
                        "/webjars/**",
                        "/swagger-resources/**",
                        "/v2/api-docs/**",
                        "/captcha",
                        "/ws/**"
                );
    }


    @Bean
    public UserDetailsService userDetailsService() {
        //重写 UserDetailsService 接口方法
        //lamda 表达 实现 接口的简化写法
        return username->{
            Admin admin = adminService.getAdminInfoByUserName(username);
            if(admin!=null){
                //设置了 全局的当前用户角色列表
                admin.setRoles(adminService.getRoles(admin.getId()));
                return admin;
            }
           // return null;
            throw new UsernameNotFoundException("用户名或密码不正确");
        };
    /*    return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                Admin admin = adminService.getAdminInfoByUserName(username);
                if(admin!=null){
                    return admin;
                }
                return null;
            }
        };*/
    }

    /**
     * security 密码处理的实例
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){

        return new JwtAuthenticationTokenFilter();
    }

}
